<?php namespace Manage;

class Agent extends Base {
	
	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'agents';

    protected $fillable = array(
        'username','password','nickname','province','city','is_created','parent_id','created_at'
    );
    protected $guarded=array(
        'id', 'password',
    );


	/**
	 * 登录数据验证
	 * @param  array $input 传入值
	 * @return [type]        [description]
	 */
	static public function loginCheck($input)
	{

		//定义变量	
		$pwd = array_pull($input, 'password');		
		$remember = array_pull($input, 'remember');

		//验证用户存在性
		$userData = Agent::where($input)->get();
		$userCount = $userData->count();
		if( empty($userCount) )
		{
			return parent::setErrorMsg('username', '不存在的用户登录!');
		}

		//验证密码
		if(!self::checkPwd($pwd, $userData[0]->password))
		{
			return parent::setErrorMsg('password', '密码错误!');
		}

		//成功验证
		if($remember == 'on')
		{
			self::rememberOpt(1, $input['username'], $pwd);
		}
		else
		{
			self::rememberOpt(0);
		}

		\Session::put('user', $input['username']);
		\Session::put('nickname', $userData[0]->nickname);
		\Session::put('id', $userData[0]->id);
		\Session::put('province', $userData[0]->province);
		\Session::put('city', $userData[0]->city);
		\Session::put('is_created', $userData[0]->is_created);
		
		return parent::setSuccessMsg('登录成功!');

	}

	/**
	 * 验证密码
	 * @param  [type] $pwd  [description]
	 * @param  [type] $retPwd  [description]
	 * @return [type]       [description]
	 */
	static public function checkPwd($pwd, $retPwd = '')
	{
		if( empty($retPwd) )
		{
			$retPwd = Agent::where('id', parent::getAgentId())->pluck('password');
		}
		return \Hash::check($pwd, $retPwd);
	}

	/**
	 * 登出操作
	 * @return [type] [description]
	 */
	static public function logout()
	{
		//登出
		if( \Session::has('user') )
		{
			\Session::forget('user');
		}
		
		if( isset($_COOKIE['user']) )
		{
			unset($_COOKIE['user']);
		}
	}

	/**
	 * 修改代理商信息
	 * @param  类型 $type 1.信息 2.密码
	 * @param  数据 $data 修改信息组
	 * @return [type]       [description]
	 */
	static public function editAll($type, $data)
	{
		//修改信息
		if( $type == 1 )
		{
			return Agent::where('id', parent::getAgentId())->update($data);
		}
		//修改密码
		elseif( $type == 2 )
		{
			$newPwd = $data['newPwd'];

			//验证密码
			$check = self::checkPwd($data['oldPwd']);

			if( ! $check )
			{
				return 0;
			}

			//验证重复密码
			if( count(array_unique($newPwd)) != 1 )
			{
				return 0;
			}

			//更新密码
			return Agent::where('id', parent::getAgentId())->update(array('password' => \Hash::make($newPwd[0])));
		}

	}

	/**
	 * 获取所有子代理商和自己数据
	 * @return [type] [description]
	 */
	static public function getAgents()
	{

		$agentId = parent::getAgentId();

        $agents=self::where('parent_id',$agentId)->lists('id');

        $agent_ids=array_merge($agents,array($agentId));

        $agents=self::whereIn('id',$agent_ids)->get();

        foreach($agents as $agent){

            $order_ids=\DB::table('agents_order')->where('agent_id',$agent->id)->lists('id');

            $agent->dev_count=\DB::table('devices')->whereIn('agents_order_id',$order_ids)->count();

            $account=\DB::table('agents_account')->where('agent_id',$agent->id)->first();

            $agent->remainder=empty($account)?0:$account->remainder;

        }

        return $agents;


	}

	/**
	 * 创建子代理商
	 * @return [type] [description]
	 */
	static public function createAgents($input)
	{
		//验证用户名
		 $agent= Agent::where('username', $input['username'])->first();

        //dd($input['create']);
		if( $agent &&$input['create'])
		{
			return array(0, '用户已存在!');
		}

		$input['parent_id'] = parent::getAgentId();

		if( $input['is_created'] = 'on' )
		{
			$input['is_created'] = 1;
		}
		else
		{
			$input['is_created'] = 0;
		}




        if($input['create'])
        {
            $input['password'] = md5($input['password']);
            $input['created_at'] = date("Y-m-d H:i:s");

            $input=array_only($input,array(
                'username','password','nickname','province','city','is_created','parent_id','created_at','mobile'
            ));
            return Agent::Insert($input);

        }else{
            $input=array_only($input,array(
                'username','password','nickname','province','city','is_created','parent_id','created_at','mobile'
            ));
            return $agent->update($input);
        }


	}
}
